package com.xm.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URISyntaxException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Properties;

public class WaterNumberGeneratorUtil {
    public static String generator(String propertiesKey) throws IOException, URISyntaxException {
        // 创建属性对象
        Properties prop = new Properties();
        // 获取属性读取文件的额绝对路径
        File file = new File("src/main/resources/waterNumber.properties");
        String absolutePath = file.getAbsolutePath();
        // 创建输入流对象
        FileInputStream fis = new FileInputStream(absolutePath);
        // 获取格式化后的当前时间（年月日）
        LocalDateTime now = LocalDateTime.now(ZoneId.of("+8"));
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        String date = dateTimeFormatter.format(now);
        // 使用InPutStream流读取properties文件
        prop.load(fis);
        // 获取key对应的value值, 获取上一个流水号
        String number = prop.getProperty(propertiesKey);
        // 截取流水号的前缀
        String serialNumber = number.substring(0, 3);
        // 将后缀转换成整数
        int num = Integer.parseInt(number.substring(10 + 1)) + 1;
        // 补零拼接
        String newWater = String.format(Integer.parseInt(serialNumber) == 100 ? "%06d" : "%04d", num);
        // 拼接当前流水号
        String waterNumber = serialNumber + date + newWater;

        prop.setProperty(propertiesKey, waterNumber);
        FileOutputStream fos = new FileOutputStream(absolutePath);
        prop.store(fos, null);
        return waterNumber;
    }
}
